package com.xit.hitmouse.ui;

import static java.security.AccessController.getContext;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
import java.util.Random;
import java.util.Vector;

//import com.example.hitmouse.R;
import com.xit.hitmouse.Bean.MapBean;
import com.xit.hitmouse.Bean.MouseBean;
import com.xit.hitmouse.R;
import com.xit.hitmouse.controller.Controller;
import com.xit.hitmouse.utils.ConvertUtils;
import com.xit.hitmouse.utils.CustomAnimation;
import com.xit.hitmouse.utils.CustomFunction;
import com.xit.hitmouse.utils.MesUtils;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.usage.UsageEvents;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class HitActivity extends Activity {

	private TextView timer;  //显示时间
	private TextView scoreView;  //显示分数
	private RelativeLayout layout;
	private RelativeLayout layoutParent;
	private Handler handler;
	private int score = 0;
	private int recLen = 30;
	Controller controller;
	Boolean musicPlay = false;

	private ValueAnimator animator; //动画效果的

	//多只地鼠
	private Vector<MouseBean> mouses = new Vector<>();
	//老鼠的血条


	public int[][] position; //洞穴位置

	private MapBean mapBean; //地图
	private int type; //模式类型  简单、中等还是困难
	private HashSet<Integer> mousePositions = new HashSet<>(); //地鼠位置
	ArrayList<Integer> mouseList;// 老鼠照片 根据不同的难度产生不同的老鼠

	private ImageView hammer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.hit_layout);
		init();
		initMap();
		initMouse();
		handlerLayout();
//		randomGenerateMoney();

		new Thread(new MyThread()).start();
	}


	//////////////////////////////
	final Handler timerHandler = new Handler() {
		public void handleMessage(Message msg) {
			int index = 0;
			switch (msg.what) {
				case 1:
					recLen--;
					timer.setText("" + recLen);
					if (recLen == 0) {
						Intent intent = new Intent(HitActivity.this, GameOver.class);
						intent.putExtra("score", score + "");
						startActivity(intent);
						controller.stop();
						HitActivity.this.finish();
					}
					break;


				default:
			}
			super.handleMessage(msg);
		}
	};

	public class MyThread implements Runnable {
		@Override
		public void run() {
			while (true) {
				try {
					Thread.sleep(1000);
					Message message = new Message();
					message.what = 1;
					timerHandler.sendMessage(message);
				} catch (Exception e) {
				}
			}
		}
	}


	private void init() {
		timer = (TextView) findViewById(R.id.timer);
		scoreView = (TextView) findViewById(R.id.score);
		layout = findViewById(R.id.layout);
		layoutParent = findViewById(R.id.layoutParent);
		controller = new Controller(HitActivity.this);

		//播放背景音乐
		if (!musicPlay) {
			controller.play();
			musicPlay = true;
		}
	}

	public void handlerLayout() {
		//当没有打到时候的处理
		layout.setOnClickListener(new OnClickListener() {
			@Override

			public void onClick(View v) {

				int count = new Random().nextInt(7); //随机出现音效
				if (count == 6) {
					controller.playSound(MesUtils.getNoTouchSound());

				}

			}

		});
		//锤子设置
		layout.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					float x = event.getRawX() - 40;
					float y = event.getRawY() - 300;
					Log.i("aaa", x + ":" + y);
					hammer = new ImageView(HitActivity.this);
					hammer.setBackgroundResource(MesUtils.getHammer());
					// 在锤击位置显示动画效果
					showHammerHitAnimation(hammer, x, y);
					layout.addView(hammer);

				}
				return true;
			}


		});
	}

	private void initMap() {
		Intent intent = getIntent();


		type = Integer.parseInt(intent.getStringExtra("maptype"));
		mapBean = new MapBean(type);

		position = mapBean.getPosition();
		//设置背景场景
		layoutParent.setBackgroundResource(mapBean.getBackground());
// 设置地图洞穴
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT, // 宽度设置为自适应
				RelativeLayout.LayoutParams.WRAP_CONTENT  // 高度设置为自适应
		);

		// 9个洞穴
		for (int i = 0; i < 9; i++) {
			final ImageView newMap = new ImageView(this);
			newMap.setImageResource(mapBean.getCave());

			// 设置洞穴大小
			layoutParams.width = ConvertUtils.dpConvertPix(this, 100);
			layoutParams.height = ConvertUtils.dpConvertPix(this, 45);
			// 设置洞穴位置
			newMap.setX(position[i][0]); // X 轴位置
			newMap.setY(position[i][1]);  // Y 轴位置
			newMap.setVisibility(View.VISIBLE);
			newMap.setLayoutParams(layoutParams);

			float x = newMap.getX();
			float y = newMap.getY();
			Log.d("MouseCoordinates11", "X: " + x + ", Y: " + y);
			//
			layout.addView(newMap);

		}

	}

	private void initMouse() {
		//添加老鼠类型  根据地图类型来设置
		mouseList = new ArrayList<>();
		mouseList.add(R.drawable.mouse_1);
		if (type != 1) {  //中等难度 这样写可以少写一次add
			mouseList.add(R.drawable.mouse_2);
		}
		if (type == 3) {
			mouseList.add(R.drawable.mouse_13);
		}

		// 生成多只地鼠
		Runnable mouseGenerator = new Runnable() {
			@Override
			public void run() {
				generateMouse();
				handler.postDelayed(this, 2001); // 间隔两秒生成一批地鼠
				//老鼠的持续显示时间
				handler.post(() -> {
					Iterator<MouseBean> iterator = mouses.iterator();
					while (iterator.hasNext()) {
						MouseBean mousebean = iterator.next();
						if (!mousebean.isLive()) {  //如果老鼠消失了
							ImageView mouse = mousebean.getMouses();
							layout.removeView(mouse);
							layout.removeView(mousebean.getMousesHp());
							iterator.remove(); // 使用迭代器安全地删除元素
							mousePositions.remove(mousebean.getMousePositions());//移除老鼠的位置
						}
					}
				}); //
			}
		};


		//消息处理器
		handler = new Handler() {
			public void handleMessage(Message msg) {

				if (msg.what == 2) {
					//判断有没有被打死
					//这里其实可以简化，直接用一个临时变量存储上一个点击的老鼠即可
					for (final MouseBean mousebean : mouses) {
						ImageView mouse = mousebean.getMouses();
						if (mousebean.isTouch()) { //很有必要！！！！ 本来觉得没必要一测试直接炸裂
							randomGenerateMoney(mouse);
							mouse.setImageResource(R.drawable.hit);
							mouse.setVisibility(View.VISIBLE);
							controller.playSound(R.raw.hit_sound);
							controller.playSound(R.raw.dizzy);

							handler.postDelayed(new Runnable() { //移除图片
								@Override
								public void run() {
									layout.removeView(mouse);
									layout.removeView(mousebean.getMousesHp());
									mouses.remove(mousebean); // 从集合中删除对应的 老鼠对象
									mousePositions.remove(mousebean.getMousePositions());//移除老鼠的位置
									layout.removeView(mousebean.getMouseTime());
								}
							}, 500); // 击中效果持续时间500ms

						}
					}
				}

				super.handleMessage(msg);
			}

		};
		handler.post(mouseGenerator); // 开始执行生成地鼠的任务

	}


	//生成多只地鼠
	private void generateMouse() {

		// 创建并设置相对布局参数  老鼠的
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT, // 宽度设置为自适应
				RelativeLayout.LayoutParams.WRAP_CONTENT  // 高度设置为自适应
		);
		// 创建并设置相对布局参数  血条的
		RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT, // 宽度设置为自适应
				RelativeLayout.LayoutParams.WRAP_CONTENT  // 高度设置为自适应
		);

		// 创建并设置相对布局参数  生存时间的
		RelativeLayout.LayoutParams layoutParams3 = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT, // 宽度设置为自适应
				RelativeLayout.LayoutParams.WRAP_CONTENT  // 高度设置为自适应
		);

		int count = new Random().nextInt(3) + 1; //随机生成老鼠的数量
		// 在一个循环中创建多只老鼠，并添加到集合中
		for (int i = 0; i < count; i++) {
			final ImageView newMouse = new ImageView(this);
			final ImageView newMouseHp = new ImageView(this); //老鼠的血条

			final ProgressBar newMouseTime = new ProgressBar
					(this, null, android.R.attr.progressBarStyleHorizontal); // 创建 ProgressBar
			//随机生成老鼠的类型
			int index2 = new Random().nextInt(mouseList.size()); //随机生成0-2的随机数
//				newMouse.setImageResource(mouseList.get(index2));


			// 设置老鼠大小
			layoutParams.width = ConvertUtils.dpConvertPix(this, 100);
			layoutParams.height = ConvertUtils.dpConvertPix(this, 90);
			// 设置老鼠血条大小
			layoutParams2.width = ConvertUtils.dpConvertPix(this, 100);
			layoutParams2.height = ConvertUtils.dpConvertPix(this, 40);

			// 设置老鼠生存时间
			layoutParams3.width = ConvertUtils.dpConvertPix(this, 90);
			layoutParams3.height = ConvertUtils.dpConvertPix(this, 4);
			// 设置老鼠的位置
			int index = getRandomUniquePosition();//生成一个随机的位置
			newMouse.setX(position[index][0]); // X 轴位置
			newMouse.setY(position[index][1] - 150);  // Y 轴位置

			// 设置老鼠血条的位置
			newMouseHp.setX(position[index][0]); // X 轴位置
			newMouseHp.setY(position[index][1] - 110);  // Y 轴位置

			// 设置老鼠倒计时的位置
			newMouseTime.setX(position[index][0] + 13); // X 轴位置
			newMouseTime.setY(position[index][1] - 50);  // Y 轴位置
			newMouseTime.setProgressDrawable(getResources().getDrawable(R.drawable.custom_progress_bar));


			//动效
			animationEffects(mouseList.get(index2), newMouse);
			animationEffects(R.drawable.l100, newMouseHp);

			animationEffects2(newMouseTime);


			// 将新创建的老鼠添加到集合中
			MouseBean mouseBean = new MouseBean();
			mouseBean.setMouses(newMouse);
			mouseBean.setMousePositions(index);
			mouseBean.setMousesHp(newMouseHp);
			mouseBean.setType(index2 + 1); //设置不同的老鼠类型
			mouseBean.setMouseTime(newMouseTime);
			mouses.add(mouseBean);
			showTime(newMouseTime, mouseBean.getLive());  //时间倒计时设置


//			newMouse.setVisibility(View.VISIBLE);
			newMouseHp.setVisibility(View.VISIBLE);
			newMouseTime.setVisibility(View.VISIBLE);
			newMouse.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {


					// 获取点击位置的坐标
					float x = v.getX() + 5;
					float y = v.getY();
					hammer = new ImageView(HitActivity.this);
					hammer.setBackgroundResource(R.drawable.hammer1);
					// 在锤击位置显示动画效果
					showHammerHitAnimation(hammer, x, y);
					layout.addView(hammer);

					Log.d("MouseCoordinates22", "老鼠被打中了");

//				Message m = new Message();
					Message m = Message.obtain();
					m.what = 2;
					mouseBean.setTouch(true);

					mouseBean.reduceHp(); //点击以后减少生命
					Log.i("mouseHp", mouseBean.getHp() + "");
					if (mouseBean.isKill()) {  // hp<=0的处理
						handler.sendMessage(m);
						score += mouseBean.getValue();
						newMouse.setEnabled(false);
					} else {   //减少血量处理
						animationEffects(R.drawable.l50, newMouseHp);

					}


					scoreView.setText(score + "");
				}
			});
			/*这种无法实现 点击两次老鼠才被击毙，因为点击抬起算两次操作
			newMouse.setOnTouchListener(new View.OnTouchListener() {
*/
			newMouse.setLayoutParams(layoutParams);
			float x = newMouse.getX();
			float y = newMouse.getY();
			Log.d("MouseCoordinates", "X: " + x + ", Y: " + y);
			// 将老鼠添加到界面上
			layout.addView(newMouse);

			newMouseHp.setLayoutParams(layoutParams2);
			newMouseTime.setLayoutParams(layoutParams3);
			layout.addView(newMouseHp);
			layout.addView(newMouseTime);


		}
	}

	// 假设显示老鼠和倒计时的方法
	private void showTime(ProgressBar newMouseTime, int time) {
		newMouseTime.setVisibility(View.VISIBLE);
		newMouseTime.setMax(30); // 设置进度条的最大值为100，代表总时间
		newMouseTime.setProgress(30); // 设置进度条的当前值为100，即初始为满格

		new CountDownTimer(time - 1000, 10) { //
			public void onTick(long millisUntilFinished) {
				long seconds = millisUntilFinished / 30;
				int progress = (int) (seconds); // 根据剩余秒数计算进度
				newMouseTime.setProgress(progress);
			}

			public void onFinish() {
				newMouseTime.setVisibility(View.GONE); // 或者移除老鼠和倒计时的布局
			}
		}.start();
	}

	private void showHammerHitAnimation(ImageView hammerImageView, float x, float y) {
		// 设置锤子图片显示在点击位置
		hammerImageView.setX(x);
		hammerImageView.setY(y);
		hammerImageView.setVisibility(View.VISIBLE);

		// 设置一个简单的动画，比如缩放动画
		hammerImageView.animate()
				.scaleX(0.8f)
				.scaleY(0.8f)
				.setDuration(200) // 动画持续时间
				.withEndAction(new Runnable() {
					@Override
					public void run() {
						// 隐藏锤子图片
						hammerImageView.setVisibility(View.INVISIBLE);
					}
				})
				.start();
	}

	private void animationEffects(int image, ImageView arg) {

		//实现逐渐显示老鼠功能
		Bitmap fullBitmap = BitmapFactory.decodeResource(getResources(), image); // 加载完整的老鼠图片
		// 假设初始显示的是腿部，裁剪出腿部的部分（假设腿部占据了图片的下半部分）
		int legHeight = fullBitmap.getHeight() / 2; // 腿部的高度，这里假设腿部在图片的下半部分
		if (image == R.drawable.l50) {
			legHeight = (int) (fullBitmap.getHeight() / 1.3);
		}
		Bitmap legBitmap = Bitmap.createBitmap(fullBitmap, 0, 0, fullBitmap.getWidth(), legHeight);
		// 将裁剪后的腿部图片显示在ImageView中
		arg.setImageBitmap(legBitmap);

		// 使用属性动画逐步显示完整的老鼠
		animator = ValueAnimator.ofInt(legHeight, fullBitmap.getHeight());
		animator.setDuration(1000); // 动画持续3秒，可根据实际情况调整

		animator.addUpdateListener(animation -> {
			int value = (int) animation.getAnimatedValue();
			// 根据动画的进度改变裁剪区域，逐步显示完整的老鼠

			Bitmap displayedBitmap = Bitmap.createBitmap(fullBitmap, 0, 0, fullBitmap.getWidth(), value);
			arg.setImageBitmap(displayedBitmap);


		});

		if (image == R.drawable.l100) {
			Log.i("asd", "1");
			//设置血条的滚动效果
			ObjectAnimator translationAnimator = ObjectAnimator.ofFloat(arg, "translationY", arg.getTranslationY(), arg.getTranslationY() - 100f);
			translationAnimator.setDuration(1000); // 设置滚动动画持续1秒
			translationAnimator.start();
		}


		animator.start();

	}

	private void animationEffects2(ProgressBar newMouseTime) {

		TranslateAnimation animation = new TranslateAnimation(0, 0, newMouseTime.getHeight(), MesUtils.getTimeBarOffset());
		animation.setDuration(800); // 设置动画持续时间为1秒
		animation.setInterpolator(new LinearInterpolator()); // 设置线性插值器，让进度条平滑地滚动

		// 添加动画监听器，在动画结束时设置进度条的位置
		animation.setAnimationListener(new Animation.AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				// 设置老鼠结束倒计时的位置
				newMouseTime.setY(newMouseTime.getY() + MesUtils.getTimeBarOffset());  // Y 轴位置

			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}
		});

		// 启动动画
		newMouseTime.startAnimation(animation);

	}

	//生成老鼠的随机位置
	private int getRandomUniquePosition() {
		int index = new Random().nextInt(position.length);
		while (mousePositions.contains(index)) {
			index = new Random().nextInt(position.length);
		}
		mousePositions.add(index);
		return index;
	}
	//随机生成钱   前提-消灭地鼠的时候
	private void randomGenerateMoney(ImageView  mouse) {
		int index = new Random().nextInt(3);
		if(index != 1){
			return;
		}
		// 创建并设置相对布局参数  生存时间的
		RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT, // 宽度设置为自适应
				RelativeLayout.LayoutParams.WRAP_CONTENT  // 高度设置为自适应
		);
		final ImageView randomMoney = new ImageView(HitActivity.this);
		randomMoney.setLayoutParams(layoutParams1);
		randomMoney.setBackgroundResource(R.drawable.money1);
		layoutParams1.width = ConvertUtils.dpConvertPix(HitActivity.this, 30);
		layoutParams1.height = ConvertUtils.dpConvertPix(HitActivity.this, 30);
		randomMoney.setX(mouse.getX()+100);
		randomMoney.setY(mouse.getY()+50);
		layout.addView(randomMoney);

		if(true){
			CustomFunction.openAutoGetMoney(randomMoney);
		}else {
			randomMoney.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					CustomFunction.openAutoGetMoney(randomMoney);
				}
			});
		}


	}




	@Override
	protected void onPause(){
		if(controller.isPlay()){
			controller.pauseMusic();
		}
		super.onPause();

	}
	@Override
	protected void onDestroy() {
		handler.removeCallbacksAndMessages(null); // 移除所有的任务和消息
		if(controller.isPlay()){
			controller.pauseMusic();
		}
		super.onDestroy();

	}
	@Override
	public void onBackPressed() {
		if (controller != null) {
			controller.stop(); // 停止音乐播放
		}
		super.onBackPressed(); // 继续返回操作
	}



}
